package org.Shiikong_Memory.SakuraBlockFrame.ExternalAPI;


import lombok.Data;
import lombok.Setter;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import org.Shiikong_Memory.SakuraBlockFrame.BasisTool.MessageTool;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;

public class PapiBuilder {
    @Setter
    private static int maxHelpItems = 5;
    private static final List<PlaceholderInfo> registeredPlaceholders = new ArrayList<>();
    // 建造者实例入口
    public static Builder builder() {
        return new Builder();
    }
    public static Builder builder(PapiInfo papiInfo) {
        Builder builder = new Builder();
        builder.setAuthor(papiInfo.getAuthor());
        builder.setVersion(papiInfo.getVersion());
        return builder;
    }

    public static class Builder {
        private String identifier;
        private String paramsName;
        private String description;
        private String author;
        private String version;
        private PapiRequestHandler requestHandler;

        // 链式调用方法
        public Builder setIdentifier(String identifier) {
            this.identifier = identifier;
            return this;
        }

        public Builder setDescription(String description) {
            this.description = description;
            return this;
        }

        public Builder setAuthor(String author) {
            this.author = author;
            return this;
        }

        public Builder setVersion(String version) {
            this.version = version;
            return this;
        }

        // 构建最终对象
        public void build() {
            if (identifier == null) {
                throw new IllegalStateException("Identifier must be set");
            }

            PlaceholderExpansion expansion =new PlaceholderExpansion() {
                @Override
                public String getIdentifier() {
                    return identifier;
                }

                @Override
                public String getAuthor() {
                    return author != null ? author : "";
                }

                @Override
                public String getVersion() {
                    return version != null ? version : "";
                }

                @Override
                public boolean persist() {
                    return true; // 保持扩展持久化
                }

                @Override
                public String onPlaceholderRequest(Player player, String params) {
                    return handleRequest(player, params);
                }

                @Override
                public String onRequest(OfflinePlayer player, String params) {
                    return handleRequest(player, params);
                }

                private String handleRequest(OfflinePlayer player, String params) {
                    if (requestHandler != null) {
                        return requestHandler.handle(player.getPlayer(), params);
                    }
                    return null; // 返回null时PAPI会自动显示原始占位符
                }
            };

            expansion.register();

            // 注册后保存帮助信息
            registeredPlaceholders.add(new PlaceholderInfo(
                    identifier,
                    paramsName != null ? paramsName : "?",
                    description != null ? description : "",
                    author != null ? author : "",
                    version != null ? version : ""
            ));
        }
    }

    public static void sendHelp(CommandSender sender, int page) {
        // 使用与CommandCore相同的分页逻辑
        int totalPages = (int) Math.ceil((double) registeredPlaceholders.size() / maxHelpItems);
        page = Math.max(1, Math.min(page, totalPages));

        MessageTool.Builder builder = MessageTool.builder()
                .addText("§6===== PAPI占位符帮助 (§e" + page + "§6/§e" + totalPages + "§6) =====");

        registeredPlaceholders.stream()
                .skip((page - 1) * (long) maxHelpItems)
                .limit(maxHelpItems)
                .forEach(info -> {
                    builder.addText("\n§7- §b%" + info.identifier + "_" + info.paramsName + "%")
                            .addText(" §f» §7" + info.description);
                });

        if (totalPages > 1) {
            builder.addText("\n\n");
            if (page > 1) {
                builder.addText("§a◀ 上一页")
                        .withClickEvent(ClickEvent.Action.RUN_COMMAND, "sb help " + (page - 1))
                        .withHoverEvent(HoverEvent.Action.SHOW_TEXT, "点击查看上一页");
            }
            if (page < totalPages) {
                if (page > 1) builder.addText(" §7| ");
                builder.addText("§a下一页 ▶")
                        .withClickEvent(ClickEvent.Action.RUN_COMMAND, "sb help " + (page + 1))
                        .withHoverEvent(HoverEvent.Action.SHOW_TEXT, "点击查看下一页");
            }
        }

        // 发送消息
        if (sender instanceof Player) {
            builder.build().sendTo((Player) sender);
        } else {
            // 控制台备用显示
            sender.sendMessage(ChatColor.stripColor(
                    builder.build().components.stream()
                            .map(c -> c.toLegacyText()) // 明确调用实例方法
                            .reduce("", (a, b) -> a + b)
            ));
        }
    }

    private record PlaceholderInfo(String identifier, String paramsName, String description, String author,
                                   String version) {
    }

    @Data
    public class PapiInfo{
        private String author;
        private String version;
    }

    @FunctionalInterface
    public interface PapiRequestHandler {
        String handle(Player player, String params);
    }
}
